package com.hlz.batch.customize;

import org.springframework.batch.core.configuration.annotation.DefaultBatchConfigurer;
import org.springframework.batch.core.launch.JobLauncher;
import org.springframework.batch.core.launch.support.SimpleJobLauncher;
import org.springframework.batch.core.repository.JobRepository;
import org.springframework.batch.core.repository.support.JobRepositoryFactoryBean;
import org.springframework.batch.core.repository.support.MapJobRepositoryFactoryBean;
import org.springframework.batch.support.transaction.ResourcelessTransactionManager;
import org.springframework.context.annotation.Bean;
import org.springframework.stereotype.Component;
import org.springframework.transaction.interceptor.TransactionProxyFactoryBean;

import java.util.Properties;

/**
 * @author Hongliang Zhu
 * @create 2023-02-26 22:50
 */
@Component
public class MyBatchConfigurer extends DefaultBatchConfigurer {

    /**
     * 自定义存储层
     *
     * @return
     * @throws Exception
     */
//    @Override
//    protected JobRepository createJobRepository() throws Exception {
//
//        MapJobRepositoryFactoryBean factory = new MapJobRepositoryFactoryBean();
//        factory.setTransactionManager(new ResourcelessTransactionManager());
//        return factory.getObject();
//
//    }


        @Override
    protected JobRepository createJobRepository() throws Exception {
        JobRepositoryFactoryBean factory = new JobRepositoryFactoryBean();
//        factory.setDataSource(dataSource);
//        factory.setTransactionManager(transactionManager);
        factory.setIsolationLevelForCreate("ISOLATION_REPEATABLE_READ");
            factory.setDatabaseType("gauss");
        // 配置表的前缀
        /**
         * 只有表前缀可以配置，表列名不可以配置
         */
        factory.setTablePrefix("BATCH_HLZ_");
        factory.setMaxVarCharLength(1000);
        return factory.getObject();
    }



    /**
     * 配置事务管理器
     *
     * @return
     * @throws Exception
     */
    @Bean
    public TransactionProxyFactoryBean baseProxy() throws Exception {
        TransactionProxyFactoryBean transactionProxyFactoryBean = new TransactionProxyFactoryBean();
        Properties transactionAttributes = new Properties();
        transactionAttributes.setProperty("*", "PROPAGATION_REQUIRED");
        transactionProxyFactoryBean.setTransactionAttributes(transactionAttributes);
        transactionProxyFactoryBean.setTarget(createJobRepository());
//        transactionProxyFactoryBean.setTransactionManager(transactionManager());
        return transactionProxyFactoryBean;
    }


    @Override
    protected JobLauncher createJobLauncher() throws Exception {
        SimpleJobLauncher jobLauncher = new SimpleJobLauncher();
        jobLauncher.setJobRepository(createJobRepository());
        jobLauncher.afterPropertiesSet();
        return jobLauncher;
    }
}
